package com.kylin.biz.helper.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 切面：记录接口方法执行时长
 * @author Damon S.
 * @version v1.0.1
 * @date 2021年01月16日 14:19
 */
@Aspect
@Slf4j
@Component
public class DurationAspect {

    @Pointcut("execution(* com.kylin.core.*.web.facade.impl.*Impl.*(..))")
    public void pointcut() {
        // this is a cut point method
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object resultData;
        Signature signature = pjp.getSignature();
        long startAt = System.currentTimeMillis();
        try {
            // 执行正常逻辑并返回
            resultData = pjp.proceed();
        } catch (Throwable e) {
            if (log.isDebugEnabled()) {
                log.info("=====>get_results_from_[{}]_error_{}",
                        signature.getDeclaringTypeName() + "." + signature.getName(),
                        e.getMessage());
            }
            throw e;
        } finally {
            if (log.isDebugEnabled()) {
                log.info("=====>get_results_from_[{}]_takes_[{}]_ms",
                        signature.getDeclaringTypeName() + "." + signature.getName(),
                        System.currentTimeMillis() - startAt);
            }
        }
        return resultData;
    }
}
